﻿package net.wangit.dev.group;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.framework.config.UnitGroups;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveGroupAction extends DomainAction {

	public SaveGroupAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newGroupId = ac.getRequestParameter("group.gid");
		if (!Checker.isEmpty(newGroupId))
			newGroupId = StringUtil.clearSpace(newGroupId.toLowerCase());
		format(ac, newGroupId);
		super.doAction(db, ac);
		ac.setSessionAttribute(GroupUI.KEY_ID, newGroupId);
		String oldGroupId = ac.getRequestParameter("group.gid.k");
		int groupType = Integer.parseInt(ac.getRequestParameter("group.t"));
		GroupReferenceUtil
				.update(db, domain, groupType, oldGroupId, newGroupId);
		UnitGroups.reload(domain);
	}

	private void format(ActionContext ac, String groupId) {
		List<Table> tables = ac.getTables();
		if (tables.size() > 0) {
			Table table = tables.get(0);
			List<ColumnRow> rows = table.getRows();
			if (rows.size() > 0) {
				ColumnRow row = rows.get(0);
				row.set("gid", groupId);
			}
		}
	}
}
